package com.smart.system.service.impl;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.smart.common.constant.GlobalConstants;
import com.smart.common.core.domain.entity.SysDept;
import com.smart.common.core.page.PageQuery;
import com.smart.common.utils.DateUtils;
import com.smart.common.utils.SecurityUtils;
import com.smart.common.utils.StringUtils;
import com.smart.system.domain.*;
import com.smart.system.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smart.system.mapper.CarMapper;

/**
 * 车辆Service业务层处理
 * 
 * @author smart
 * @date 2024-09-18
 */
@Service
public class CarServiceImpl extends ServiceImpl<CarMapper,Car> implements ICarService {

    @Autowired
    @Lazy
    private ICarTrajectoryService carTrajectoryService;

    @Lazy
    @Autowired
    private IAreaCarService areaCarService;
    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private ICarClassifyService carClassifyService;

    /**
     * 查询车辆
     * 
     * @param id 车辆主键
     * @return 车辆
     */
    @Override
    public Car selectCarById(String id)
    {
        return this.baseMapper.selectById(id);
    }

    /**
     * 查询车辆列表
     * 
     * @param car 车辆
     * @return 车辆
     */
    @Override
    public IPage<Car> selectCarList(Car car, PageQuery paeQuery)
    {
        Page<Car> page = null;
        LambdaQueryWrapper<Car> query = Wrappers.lambdaQuery(Car.class);
        query.like(car!=null&&StringUtils.isNotEmpty(car.getName()),Car::getName,car.getName()).like(car!=null&& StringUtils.isNotEmpty(car.getCarNumber()),Car::getCarNumber,car.getCarNumber());
        if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            List<SysDept> deptIds = deptService.listDeptChildById(SecurityUtils.getDeptId());
            page = this.page(paeQuery.toPage(), query.in(deptIds.size()>0,Car::getDeptId,deptIds.stream().map(SysDept::getDeptId).collect(Collectors.toList())));
        }else{
            page = this.page(paeQuery.toPage(),query);
        }
        List<Car> records = page.getRecords();
        for (Car record : records) {
            //获取车辆最会更新时间
            CarTrajectory one = carTrajectoryService.getOne(Wrappers.lambdaQuery(CarTrajectory.class)
                    .eq(CarTrajectory::getCarId,record.getId())
                    .orderByDesc(CarTrajectory::getCreateTime)
                    .last("limit 1"), false);
            //获取部门名称
            SysDept sysDept = deptService.selectDeptById(Long.parseLong(record.getDeptId()));
            if(sysDept!=null){
                record.setDeptName(sysDept.getDeptName());
            }
            //获取驾驶人名称
            Employee employee = employeeService.selectEmployeeById(record.getDriverId());
            if(employee!=null){
                record.setDriverPhone(employee.getPhone());
                record.setDriverName(employee.getName());
            }
            CarClassify carClassify = carClassifyService.getById(record.getClassify());
            if(carClassify!=null){
                record.setClassifyName(carClassify.getClassName());
            }
            //获取分类名称
            record.setCarTrajectory(one);
        }
        return page;
    }

    /**
     * 新增车辆
     * 
     * @param car 车辆
     * @return 结果
     */
    @Override
    public int insertCar(Car car)
    {
        car.setCreateTime(DateUtils.getNowDate());
        car.setStatus(GlobalConstants.SUCCESS);
        if(car.getDeptId() == null){
            car.setDeptId(String.valueOf(SecurityUtils.getDeptId()));
        }
        return this.baseMapper.insert(car);
    }

    /**
     * 修改车辆
     * 
     * @param car 车辆
     * @return 结果
     */
    @Override
    public int updateCar(Car car)
    {
        car.setUpdateTime(DateUtils.getNowDate());
        return this.baseMapper.updateById(car);
    }

    /**
     * 批量删除车辆
     * 
     * @param ids 需要删除的车辆主键
     * @return 结果
     */
    @Override
    public int deleteCarByIds(String[] ids)
    {
        return this.baseMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除车辆信息
     *
     * @param id 车辆主键
     * @return 结果
     */
    @Override
    public int deleteCarById(String id)
    {
        return this.baseMapper.deleteById(id);
    }

    @Override
    public boolean changeStatus(Integer id,Integer status) {
        this.update(Wrappers.lambdaUpdate(Car.class).set(Car::getStatus,status).eq(Car::getId,id));
        return true;
    }

    @Override
    public IPage<Car> listCar(Integer areaId, Page toPage) {
        LambdaQueryWrapper<AreaCar> query = Wrappers.lambdaQuery(AreaCar.class);
        if(areaId == null){
            query.in(AreaCar::getAreaId, areaId);
        }else{
            query.eq(AreaCar::getAreaId, areaId);
        }
        Page<AreaCar> page = areaCarService.page(toPage,query);
        List<AreaCar> records = page.getRecords();

        Page<Car> carPage = new Page<>();
        BeanUtils.copyProperties(page,carPage);
        List<Car> linkedList = new LinkedList<>();
        if (records.size()>0) {
            List<Integer> carIds = records.stream().map(AreaCar::getCarId).collect(Collectors.toList());
            linkedList = this.listByIds(carIds);
            //根据driverId员工
            List<Employee> employees = employeeService.listByIds(linkedList.stream().map(Car::getDriverId).collect(Collectors.toList()));
            for (Car car : linkedList) {
                for (Employee employee : employees) {
                    if (car.getDriverId() != null&&Integer.parseInt(car.getDriverId())==employee.getId()){
                        car.setDriverName(employee.getName());
                        car.setDriverPhone(employee.getPhone());
                    }
                }

            }
        }
        carPage.setRecords(linkedList);
        return carPage;
    }

    @Override
    public CarTrajectory getLocation(Integer carId) {
        CarTrajectory newData = carTrajectoryService.getNewData(carId);
        return newData;
    }
}
